<template>
  <div class="app-container">
    <el-button type="primary" @click="addRole">添加</el-button>
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" v-loading.body="listLoading" border>
      <el-table-column align="center" label="序号" width="100">
        <template scope="scope">
          {{scope.row.index}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" width="200">
        <template scope="scope">
          {{scope.row.roleName}}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="角色描述" width="300">
        <template scope="scope">
          {{scope.row.description}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </div>
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'添加角色'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="role.roleName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="role.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea"
            placeholder="角色描述" />
        </el-form-item>

        <el-form-item label="权限">
          <el-tree ref="tree" default-expand-all :check-strictly="checkStrictly" :data="routes" :props="defaultProps"
            show-checkbox node-key="id" class="permission-tree" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { page, add, getMenuTree, getRoleMenu } from 'api/role'
  const defaultRole = {
    id: '',
    roleName: '',
    description: '',
    routes: []
  }
  export default {
    data() {
      return {
        rolesList: [],
        role: Object.assign({}, defaultRole),
        routes: [],
        dialogVisible: false,
        dialogType: 'new',
        listLoading: true,
        checkStrictly: false,
        total: 10,
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined
        }
      }
    },
    created() {
      // this.listLoading = true
      // this.rolesList.push({ 'name': 'admin', 'desc': '管理员' })
      // setTimeout(() => {
      //   this.listLoading = false
      // }, 1000);
      this.getlist()
      // console.log(this.rolesList);
    },
    computed: {
    },
    methods: {
      async getRoleTree() {
        getMenuTree().then(response => {
          this.routes = response.data;
          console.log(response.data)
          this.$refs.tree.store.defaultExpandAll = true;
          return Promise.resolve(true)
        })
      },
      getlist() {
        this.listLoading = true
        page(this.listQuery).then(response => {
          var data = response.data
          this.rolesList = data.rows;
          this.total = data.total;
          this.listLoading = false;
          for (var ix in this.rolesList) {
            this.rolesList[ix].index = parseInt(ix, 10) + 1;
          }
          this.listLoading = false
        })
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
      },
      addRole() {
        this.dialogType = 'new'
        this.dialogVisible = true
        this.role = Object.assign({}, defaultRole)
        this.role.status = 1
        this.getRoleTree()

      },
      getRoleMenuIds(menuTree, menuIds, result) {
        if (menuTree.children == null || menuTree.children.length == 0) {
          if (menuIds.indexOf(menuTree.id) > -1) {
            result.push(menuTree.id);
          }
        } else {
          for (var i in menuTree.children) {
            this.getRoleMenuIds(menuTree.children[i], menuIds, result)
          }
        }
      },
      handleEdit(scope) {
        this.dialogType = 'edit'
        this.dialogVisible = true
        this.role.roleName = scope.row.roleName
        this.role.description = scope.row.description
        this.role.status = 1
        this.role.id = scope.row.id
        this.getRoleTree().then(() => {
          getRoleMenu(scope.row.id).then(response => {
            if (response.status != 200) {
              this.$error(response.message)
              return
            }
            var roleMenuIds = []
            var result = []
            for (var i in response.data) {
              roleMenuIds.push(response.data[i].id)
            }

            this.getRoleMenuIds(this.routes[0], roleMenuIds, result)
            console.log(result)
            this.$refs.tree.setCheckedKeys(result)

          })
        })

      },
      confirmRole() {
        var role = this.role;
        if (role.roleName == undefined || role.roleName == '') {
          this.$error('请输入角色名称')
          return;
        }
        var nodes = this.$refs.tree.getHalfCheckedNodes().concat(this.$refs.tree.getCheckedNodes())
        if (nodes.length == 0) {
          this.$error('请选择菜单')
          return;
        }
        var menuIds = []
        for (var i in nodes) {
          menuIds.push(nodes[i].id)
        }
        var obj = {}
        obj.roleName = this.role.roleName
        obj.description = this.role.description
        obj.menuIds = menuIds
        obj.status = this.role.status
        if (this.role.id != undefined) {
          obj.id = this.role.id
        }
        add(obj).then(response => {
          if (response.status == 200) {
            this.getlist()
            this.$success('保存成功')
          } else {
            this.$error(response.message)
          }
          const isEdit = this.dialogType === 'edit'
          this.dialogVisible = false
        })


      }
    },

  }
</script>